import { useState } from "react";
import Taro from "@tarojs/taro";
import { requestUpload } from "@/utils/request";

import ApiApp from "@/api/app";

type UseUpload = {
  action?: string;
  onSuccess?: (urls: string[]) => void;
};

export default ({ action = ApiApp.uploadFile, onSuccess }: UseUpload = {}) => {
  const [loading, setLoading] = useState(false);

  // 上传
  const runUpload = async (tempFilePath) => {
    const res = await requestUpload(action, tempFilePath, {
      formData: {
        filename: tempFilePath.match(/\/([^\/?#]+)$/)[1],
      },
    });

    console.log("===图片上传成功", res);
    return res.url;
  };

  // 批量统一开始上传
  const upload = (tempFiles) => {
    if (action) {
      setLoading(true);
      Taro.showLoading({ title: "上传中，请耐心等待" });

      Promise.allSettled(tempFiles.map(runUpload))
        .then((res) => {
          console.log("===批量上传成功", res);

          const list = res
            .map((e) => (e.status === "fulfilled" ? e.value : ""))
            .filter((e) => !!e);

          const { length } = list;

          if (length == 0) return Promise.reject();

          const failNum = tempFiles.length - length;
          Taro.showToast({
            title:
              failNum === 0
                ? "上传成功"
                : `上传成功${length}张，失败${failNum}张`,
          });
          onSuccess?.(list);
        })
        .catch((err) => {
          console.log("err", err);
          Taro.showToast({ title: "上传失败", icon: "error" });
        })
        .finally(() => {
          setLoading(false);
        });
    }
  };

  return {
    loading,
    upload,
  };
};
